<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\helper;

class SQLHelper
{
    /**
     * 解析数据库语句函数
     * @param string $sql  带默认前缀的sql语句
     * @param string $tablepre  当前系统前缀
     * @return multitype:string 返回最终需要的sql语句
     */
    public static function sql_split($sql, $tablepre)
    {
        if ($tablepre != "sf_") {
            $sql = str_replace("EXISTS `sf_", 'EXISTS `' . $tablepre, $sql);
            $sql = str_replace("TABLE `sf_", 'TABLE `' . $tablepre, $sql);
            $sql = str_replace("LOCK TABLES `sf_", 'LOCK TABLES `' . $tablepre, $sql);
            $sql = str_replace("INSERT INTO `sf_", 'INSERT INTO `' . $tablepre, $sql);
        }
        $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
//         if ($r_tablepre != $s_tablepre) {
//             $sql = str_replace($s_tablepre, $r_tablepre, $sql);
//         }
        $sql          = str_replace("\r", "\n", $sql);
        $ret          = array();
        $num          = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries   = explode("\n", trim($query));
            $queries   = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-') {
                    $ret[$num] .= $query;
                }
            }
            $num++;
        }
        return $ret;
    }

    /**
     * 执行文件中SQL语句函数
     * @param string $file sql语句文件路径
     * @param string $tablepre  自己的前缀
     * @return multitype:string 返回最终需要的sql语句
     */
    public static function execute_sql_from_file($file, $tokens = null)
    {
        $sql_data = file_get_contents($file);
        if (!$sql_data) {
            return true;
        }

        if ($tokens) {
            $sql_data = StringHelper::replace_token($sql_data, $tokens);
        }

        $sql_format = self::sql_split($sql_data, config('database.prefix'));
        $counts = count($sql_format);
        for ($i = 0; $i < $counts; $i++) {
            $sql = trim($sql_format[$i]);
            \think\Db::execute($sql);
        }
        return true;
    }
}
